<?php
/*
 * @Description:高危许可证管理
 * @FilePath: \auxface_certificate\app\certificate\controller\user\v1\CheckList.php
 */

declare(strict_types=1);

namespace app\certificate\controller\user\v1;

use DateTime;
use think\facade\Db;
use think\Request;

class CheckList
{
    /**
     * @Description: 获取许可证类型列表
     * @param {Request} $request
     */
    public function getTypeList(Request $request)
    {
        $searchWhere = [
            ['rt.projectCode', '=', $request->prjCode],
            ['rt.dayFormUuid', '<>', ''],
            ['aw.wxappUserUuid', '=', $request->uuid],
            ['rt.isDelete', '=', 0],
            ['aw.isDelete', '=', 0],
            ['au.isDelete', '=', 0],
        ];
        $list = DB::table('certificate_heavyMachineCheckType')
            ->alias('rt')
            ->join('certificate_areaType at', 'at.typeUuid = rt.uuid')
            ->join('certificate_areaWorker aw', 'aw.areaUuid = at.areaUuid')
            ->join('certificate_heavyMachineCheckTypeAuth au', 'au.typeUuid=rt.uuid')
            ->order(['rt.id desc'])
            ->where($searchWhere)
            ->field(['rt.name', 'rt.uuid', 'rt.subtitle'])
            ->distinct(true)
            ->select()->toArray();

        return result(SUCCESS, $list, '');
    }

    /**
     * 许可证类型类型
     *
     * @param Request $request
     * @return void
     */
    public function getTypeDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $searchWhere = [
            ['rt.projectCode', '=', $request->prjCode],
            ['rt.dayFormUuid', '<>', ''],
            ['aw.wxappUserUuid', '=', $request->uuid],
            ['rt.isDelete', '=', 0],
            ['aw.isDelete', '=', 0],
            ['au.isDelete', '=', 0],
            ['au.typeUuid', '=', $uuid],
        ];
        $auth = DB::table('certificate_heavyMachineCheckType')
            ->alias('rt')
            ->join('certificate_areaType at', 'at.typeUuid = rt.uuid')
            ->join('certificate_areaWorker aw', 'aw.areaUuid = at.areaUuid')
            ->join('certificate_heavyMachineCheckTypeAuth au', 'au.typeUuid=rt.uuid')
            ->where($searchWhere)
            ->find();
        if (empty($auth)) return result(FAIL, '', '您没有权限查看');

        $where = [
            'rt.isDelete' => 0,
            'rt.uuid' => $uuid
        ];
        //查看有没有提交过的记录
        $riskData = DB::table('certificate_heavyMachineCheckType')
            ->alias('rt')
            ->join('certificate_formtemplate fd', 'fd.uuid=rt.dayFormUuid', 'left')
            ->join('certificate_formtemplate fw', 'fw.uuid=rt.weekFormUuid', 'left')
            ->join('certificate_formtemplate fa', 'fa.uuid=rt.auditFormUuid', 'left')
            ->where($where)
            ->field(['fd.fields as dayFormData', 'fw.fields as weekFormData', 'fa.fields as auditFormData', 'rt.name', 'rt.uuid'])
            ->findOrEmpty();
        if (!$riskData) return result(FAIL, '', '獲取失敗，請返回重試');
        $riskData['dayFormData'] = json_decode(html_entity_decode($riskData['dayFormData'] ?? ''), true) ?: [];
        $riskData['weekFormData'] = json_decode(html_entity_decode($riskData['weekFormData'] ?? ''), true) ?: [];
        $riskData['auditFormData'] = json_decode(html_entity_decode($riskData['auditFormData'] ?? ''), true) ?: [];
        return result(SUCCESS, $riskData, '');
    }

    /**
     * @Description: 获取检查表列表
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data  = $request->data;
        $limit =  $data['limit'];
        $page =  $data['page'];
        $status = $data['status'];
        $searchWhere = [
            ['r.isDelete', '=', '0'],
        ];
        if (!empty($data['name'])) array_push($searchWhere, ['rt.name|r.title', 'like', "%" . $data['name'] . "%"]);
        if (!empty($data['machineSn'])) array_push($searchWhere, ['r.machineSn', '=', $data['machineSn']]);
        if (!empty($data['machineUuid'])) array_push($searchWhere, ['r.machineUuid', '=', $data['machineUuid']]);

        // 获取当前用户具有每周+审核权限的类型Uuid
        $auditedTypeUuids = DB::table('certificate_heavyMachineCheckTypeAuth')
            ->alias('a')
            ->join('certificate_areaWorker w', 'w.wxappUserUuid = a.wxappUserUuid')
            ->where('a.wxappUserUuid', $request->uuid)
            ->where('w.isDelete', 0)
            ->where('a.isDelete', 0)
            ->where(function ($query) {
                $query->where('a.isWeek', 1)->whereOr('a.isAudit', 1);
            })
            ->column('a.typeUuid') ?: [];
        // 组合条件：筛选用户自己申请的记录或者用户具有每周+审核权限的记录
        array_push($searchWhere, function ($query) use ($auditedTypeUuids, $request) {
            $query->where(function ($q) use ($request) {
                // 用户自己申请的记录
                $q->where('r.wxappUserUuid', '=', $request->uuid);
            })
                ->whereOr(function ($q) use ($auditedTypeUuids) {
                    // 用户有审核权限的记录
                    if (!empty($auditedTypeUuids)) {
                        $q->whereIn('r.typeUuid', $auditedTypeUuids);
                    }
                });
        });

        $currentDate = date('Y-m-d'); // 当前时间
        //状态,使用中-1,已审批-2, 过期未审批-3
        if ($status == '1') { // 使用中
            $searchWhere[] = ['r.weekStartDate', '<=', $currentDate];
            $searchWhere[] = ['r.weekEndDate', '>=', $currentDate];
            $searchWhere[] = ['r.status', '=', 1];
        } elseif ($status == '2') { // 已审批
            $searchWhere[] = ['r.status', '=', 2];
        } elseif ($status == '3') { // 过期未审批
            $searchWhere[] = ['r.weekEndDate', '<', $currentDate];
            $searchWhere[] = ['r.status', '=', 1];
        }


        $list =  DB::table('certificate_heavyMachineCheck')
            ->alias('r')
            ->leftjoin('certificate_heavyMachineCheckType rt', 'r.typeUuid = rt.uuid')
            ->leftjoin('certificate_digitalmachine m', 'm.uuid = r.machineUuid')
            ->where($searchWhere)
            ->order(['r.id desc'])
            ->page((int)$page, (int)$limit)
            ->field(['rt.name as typeName', 'r.inDate', 'r.status', 'r.uuid', 'r.serialNumber', 'r.owner', 'rt.subtitle', 'r.title', 'r.weekEndDate','m.name as machineName'])
            ->group('r.id')
            ->select()->toArray();
        foreach ($list as &$item) {
            $typeName = DB::table('certificate_digitalmachinetype')->where("uuid", $item['digitalMacineTypeUuid'])->value('name');
            
            // $item['machineName'] = $typeName.'-'.$item['prjMachineCode'].'號機';


            //本周提交数据
            $item['currentWeekNums'] =  DB::table('certificate_heavyMachineCheckRecord')->where('checkUuid', $item['uuid'])->where('type', 1)->count();
            //当天提交数据
            $item['todayNums'] =  DB::table('certificate_heavyMachineCheckRecord')->where('checkUuid', $item['uuid'])->where('type', 1)->whereDay('checkDate')->count();
            //每周提交数据
            $item['everyWeekNums'] =  DB::table('certificate_heavyMachineCheckRecord')->where('checkUuid', $item['uuid'])->where('type', 2)->count();
            $item['inDate'] = date('Y-m-d', strtotime($item['inDate']));
        }
        foreach ($list as &$item) {
             //状态,使用中-1,已审批-2, 过期未审批-3
            if ($item['status'] == 1 && strtotime($item['weekEndDate']) < strtotime(date('Y-m-d'))) {
                $item['status'] = '3';
            }
        }
        $result['list'] = $list;
        //是否有新增权限
        $result['hasAuth'] = $this->hasAuth($request, $data);

        return result(SUCCESS, $result, '');
    }

    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];
        $where = [
            'isDelete' => 0,
            'uuid' => $uuid
        ];
        //查看有没有提交过的记录
        $checkListdata = DB::table('certificate_heavyMachineCheck')
            ->alias('r')
            ->where($where)
            ->order('id DESC')
            ->field(['r.wxappUserUuid', 'r.inDate', 'r.status', 'r.uuid', 'r.serialNumber', 'r.owner', 'r.typeUuid', 'r.weekStartDate', 'r.weekEndDate'])
            ->findOrEmpty();
        if (!$checkListdata) return result(FAIL, '', '獲取失敗，請返回重試');
        if ($checkListdata['status'] == 1 && strtotime($checkListdata['weekEndDate']) < strtotime(date('Y-m-d'))) {
            $checkListdata['status'] = 3;
        }
        //是否有申请权限
        $auth = DB::table('certificate_areaWorker')->alias('a')
            ->leftjoin('certificate_areaType t', 't.areaUuid=a.areaUuid')
            ->leftjoin('certificate_heavyMachineCheckTypeAuth au', 'au.typeUuid=t.typeUuid')
            ->where('au.typeUuid', $checkListdata['typeUuid'])
            ->where('a.isDelete', 0)
            ->where('au.isDelete', 0)
            ->where(function ($query) {
                $query->where('isDay', 1)->whereOr('isWeek', 1)->whereOr('isAudit', 1);
            })
            ->where('a.wxappUserUuid', '<>', $request->uuid)->find();
        if (empty($auth)) return result(FAIL, '', '您没有权限查看');

        //这个区域的这个类型下面，当前登录的用户权限
        $auth = DB::table('certificate_heavyMachineCheckTypeAuth')->where('wxappUserUuid', $request->uuid)->where('typeUuid', $checkListdata['typeUuid'])->find();
        $checkListdata['isDay'] = $auth['isDay'] ?? 0;
        $checkListdata['isWeek'] = $auth['isWeek'] ?? 0;
        $checkListdata['isAudit'] = $auth['isAudit'] ?? 0;

        //每日提交数据
        $checkListdata['dayRecordData'] = DB::table('certificate_heavyMachineCheckRecord')->where('checkUuid', $uuid)->where('type', 1)->field(['uuid', 'checkDate', 'formData'])->select();
        foreach ($checkListdata['dayRecordData'] as $key => $value) {
            $value['checkDate'] = date('Y-m-d', strtotime($value['checkDate']));
            $value['formData'] = json_decode(html_entity_decode($value['formData'] ?? ''), true) ?: [];
            $checkListdata['dayRecordData'][$key] = $value;
        }
        //每周提交数据
        $checkListdata['weekRecordData'] = DB::table('certificate_heavyMachineCheckRecord')->where('checkUuid', $uuid)->where('type', 2)->value('formData');
        $checkListdata['weekRecordData'] = json_decode(html_entity_decode($checkListdata['weekRecordData'] ?? ''), true) ?: [];
        //审核人员提交数据
        $checkListdata['auditRecordData'] = DB::table('certificate_heavyMachineCheckRecord')->where('checkUuid', $uuid)->where('type', 3)->value('formData');
        $checkListdata['auditRecordData'] = json_decode(html_entity_decode($checkListdata['auditRecordData'] ?? ''), true) ?: [];

        $weekStartDate = $checkListdata['weekStartDate'];
        $weekEndDate = $checkListdata['weekEndDate'];

        // 转换为 DateTime 对象
        $startDate = new DateTime($weekStartDate);
        $endDate = new DateTime($weekEndDate);
        // 创建一个空数组来存储结果
        $datesWithWeekdays = [];
        // 使用 DateInterval 来遍历每一天
        while ($startDate <= $endDate) {
            // 获取当前日期的星期几
            $weekday = $startDate->format('D');  // 'l' 返回完整的星期几名称（如：Monday, Tuesday）
            //当前日期是否申请
            $dayRecord = DB::table('certificate_heavyMachineCheckRecord')->where('checkUuid', $uuid)->where('type', 1)->where('checkDate', $startDate->format('Y-m-d'))->field(['uuid', 'checkDate', 'formData'])->find();
            $isSubmited =  $dayRecord ? 1 : 0;
            // 将日期和星期几存入数组
            $datesWithWeekdays[] = [
                'date'       => $startDate->format('Y-m-d'),   //格式化日期为 'YYYY-MM-DD'
                'weekday'    => $weekday,                      //星期几
                'isSubmited' => $isSubmited,                   //是否提交,是-1，否-0
                'formData'   => json_decode(html_entity_decode($dayRecord['formData'] ?? ''), true) ?: [],        //提交数据
            ];
            // 移动到下一天
            $startDate->modify('+1 day');
        }
        $checkListdata['weekdays'] = $datesWithWeekdays;

        //查看有没有提交过的记录
        $typeData = DB::table('certificate_heavyMachineCheckType')
            ->alias('rt')
            ->join('certificate_formtemplate fd', 'fd.uuid=rt.dayFormUuid', 'left')
            ->join('certificate_formtemplate fw', 'fw.uuid=rt.weekFormUuid', 'left')
            ->join('certificate_formtemplate fa', 'fa.uuid=rt.auditFormUuid', 'left')
            ->where('rt.uuid', $checkListdata['typeUuid'])
            ->field(['fd.fields as dayFormData', 'fw.fields as weekFormData', 'fa.fields as auditFormData', 'rt.name', 'rt.uuid'])
            ->findOrEmpty();
        $checkListdata['templateData']['dayFormData'] = json_decode(html_entity_decode($typeData['dayFormData'] ?? ''), true) ?: [];
        $checkListdata['templateData']['weekFormData'] = json_decode(html_entity_decode($typeData['weekFormData'] ?? ''), true) ?: [];
        $checkListdata['templateData']['auditFormData'] = json_decode(html_entity_decode($typeData['auditFormData'] ?? ''), true) ?: [];
        return result(SUCCESS, $checkListdata, '');
    }

    /**
     * @Description: 新增检查表
     * @param {Request} $request
     */
    public function create(Request $request)
    {
        $data  = $request->data;
        $wxappUserUuid = $request->uuid;

        $machine = DB::table('certificate_digitalMachine')
            ->alias('m')
            ->join('certificate_digitalMachineType t', 't.uuid = m.digitalMacineTypeUuid')
            ->where(['m.isDelete' => 0, 'm.uuid' => $data['machineUuid']])->field('t.machineRiskTypeUuid')
            ->field('t.heavyMachineCheckTypeUuid,m.machineSn,m.corpCode')
            ->find();
            
        if (!$machine) {
            return result(FAIL, '', '设备不存在');
        }else if(!$machine['heavyMachineCheckTypeUuid']) {
            return result(FAIL, '', '设备未关联重型许可证');
        }

        $typeUuid = $machine['heavyMachineCheckTypeUuid'];
        $type = DB::table('certificate_heavyMachineCheckType')->where(['isDelete' => 0, 'uuid' => $typeUuid])->find();
        if (!$type)  return result(FAIL, '', '许可证类型已被删除或错误！');

        $auth = DB::table('certificate_heavyMachineCheckTypeAuth')->alias('a')
            ->join('certificate_areaType t', 't.typeUuid=a.typeUuid')
            ->join('certificate_areaWorker w', 'w.areaUuid=t.areaUuid')
            ->where('a.typeUuid', $typeUuid)
            ->where('a.wxappUserUuid', $request->uuid)
            ->where('w.isDelete', 0)
            ->where('a.isDelete', 0)
            ->where('a.isDay', 1)
            ->find();
        if (empty($auth)) return result(FAIL, '', '您没有新增权限');

        $currentDate = date('Y-m-d'); // 当前时间
        //檢查該設備是否已經申請周表
        $searchWhere = [
            ['machineUuid', '=', $data['machineUuid']],
            ['weekStartDate', '<=', $currentDate],
            ['weekEndDate', '>=', $currentDate],
            ['status', '=', 1],
        ];
            
        $submitCheck =  DB::table('certificate_heavyMachineCheck')
        ->where($searchWhere)
        ->value('id');
        if($submitCheck) return result(FAIL, '', '該設備已申請檢查表');
            
        DB::startTrans();
        try {
            $weekUser =  DB::table('certificate_heavyMachineCheckTypeAuth')
                ->alias('rta')
                ->join('certificate_areaType at', 'at.areaUuid=rta.typeUuid')
                ->where('at.areaUuid', $data['areaUuid'])
                ->where('rta.typeUuid', $typeUuid)
                ->where('rta.isWeek', 1)
                ->find();
            $auditUser =  DB::table('certificate_heavyMachineCheckTypeAuth')
                ->alias('rta')
                ->join('certificate_areaType at', 'at.areaUuid=rta.typeUuid')
                ->where('at.areaUuid', $data['areaUuid'])
                ->where('rta.typeUuid', $typeUuid)
                ->where('rta.isAudit', 1)
                ->find();

            // 获取当前日期
            $today = new DateTime();
            // 获取当前周的周一日期
            $startOfWeek = clone $today;
            $startOfWeek->modify('monday this week');  // 获取本周的周一
            // 以 YYYY-MM-DD 格式输出日期
            $startOfWeekDate = $startOfWeek->format('Y-m-d');  // 格式化为 YYYY-MM-DD

            // 获取当前周的周日日期
            $endOfWeek = clone $today;
            $endOfWeek->modify('sunday this week');  // 获取本周的周日
            // 以 YYYY-MM-DD 格式输出日期
            $endOfWeekDate = $endOfWeek->format('Y-m-d');  // 格式化为 YYYY-MM-DD
            
          
            
            
            
            $saveData = [
                'machineUuid'    => $data['machineUuid'],
                'typeUuid'       => $typeUuid,
                'wxappUserUuid'  => $wxappUserUuid,
                'status'         => 0,
                'uuid'           => createUuid(),
                'areaUuid'       => $data['areaUuid'],
                'serialNumber'   => $type['serialNumber'],
                'title'          => $type['title'],
                'machineSn'      => $machine['machineSn'],
                'owner'          => $machine['corpCode'],
                'manageUserUuid' => $weekUser['wxappUserUuid'] ?? '',
                'auditUserUuid'  => $auditUser['wxappUserUuid'] ?? '',
                'weekStartDate'  => $startOfWeekDate,
                'weekEndDate'    => $endOfWeekDate,
                'status'         => 1,
                'projectCode'    => $request->prjCode,
                'corpCode'       => $request->corpCode,
            ];
            DB::table('certificate_heavyMachineCheck')->insert($saveData);
            DB::commit();
            return result(SUCCESS, ['uuid' => $saveData['uuid']], '提交成功');
        } catch (\Exception $e) {
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    /**
     * @Description: 检查记录提交
     * @param {Request} $request
     */
    public function checkRecordSubmit(Request $request)
    {
        $data  = $request->data;
        $wxappUserUuid = $request->uuid;

        $checkUuid = $data['checkUuid'];
        $formData = html_entity_decode($data['formData']);
        $check = DB::table('certificate_heavyMachineCheck')->where(['isDelete' => 0, 'uuid' => $checkUuid])->find();
        if (!$check)  return result(FAIL, '', '检查表已被删除或错误！');

        $auth = DB::table('certificate_heavyMachineCheckTypeAuth')->alias('a')
            ->join('certificate_areaType t', 't.typeUuid=a.typeUuid')
            ->join('certificate_areaWorker w', 'w.areaUuid=t.areaUuid')
            ->where('a.typeUuid', $check['typeUuid'])
            ->where('a.wxappUserUuid', $request->uuid)
            ->where('w.isDelete', 0)
            ->where('a.isDelete', 0)
            ->where(function ($query) use ($data) {
                if ($data['type'] == 1) {
                    $query->where('isDay', 1);
                } else if ($data['type'] == 2) {
                    $query->where('isWeek', 1);
                } else if ($data['type'] == 3) {
                    $query->where('isAudit', 1);
                }
            })
            ->find();
        // if (empty($auth)) return result(FAIL, '', '您没有提交权限');

        DB::startTrans();
        try {
            $recordData = [
                'checkUuid'     => $checkUuid,
                'wxappUserUuid' => $wxappUserUuid,
                'uuid'          => createUuid(),
                'formData'      => $formData,
                'typeUuid'      => $check['typeUuid'],
                'areaUuid'      => $check['areaUuid'],
                'type'          => $data['type'],
            ];
            $existWhere = [];
            switch ($data['type']) {
                case 1: //每日权限
                    array_push($existWhere, ['checkDate', '=', $data['checkDate']]);
                    $recordData['checkDate'] = $data['checkDate'];
                    //校验提交日期是否正确
                    if (strtotime($data['checkDate']) < strtotime($check['weekStartDate']) || strtotime($data['checkDate']) > strtotime($check['weekEndDate'])) {
                        return result(FAIL, '', "请提交{$check['weekStartDate']}到{$check['weekEndDate']}期间的日期");
                    }
                    break;
                case 2: //每周权限
                    array_push($existWhere, ['type', '=', 2]);
                    $recordData['checkDate'] = date('Y-m-d H:i:s');
                    DB::table('certificate_heavyMachineCheck')->where(['isDelete' => 0, 'uuid' => $checkUuid])->update(['manageUserUuid' => $request->uuid]);
                    break;
                case 3: //审核权限
                    $recordData['checkDate'] = date('Y-m-d H:i:s');
                    DB::table('certificate_heavyMachineCheck')->where(['isDelete' => 0, 'uuid' => $checkUuid])->update(['status' => 2, 'auditTime' => date('Y-m-d H:i:s'), 'auditUserUuid' => $request->uuid]);
                    break;
            }

            //重复记录查看
            array_push($existWhere, ['type', '=', $data['type']]);
            $info = DB::table('certificate_heavyMachineCheckRecord')->where('checkUuid', $checkUuid)->where($existWhere)->find();
            if ($info) return result(FAIL, '', '提交记录已经存在，请不要重复提交');

            //签名记录校验
            if (in_array($data['type'], [2, 3])) {
                //每周+审核权限需要签名
                $formData2 = json_decode(html_entity_decode($formData), true) ?? [];
                $isSigned = 0;
                //必须要有签名字段
                foreach ($formData2 as $key => $value) {
                    if ($value['tag'] == 'signature') {
                        $isSigned = 1;
                    }
                }
                if ($isSigned == 0)  return result(FAIL, '', '缺少签名字段');
            }

            DB::table('certificate_heavyMachineCheckRecord')->insert($recordData);
            DB::commit();
            return result(SUCCESS, '', '提交成功');
        } catch (\Exception $e) {
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    /**
     * @Description: 获取字典
     * @param {Request} $request
     */
    public function getOptions(Request $request)
    {
        $where = array_merge(['isDelete' => 0], $request->authWhere);

        $data['areaList'] = DB::table('certificate_area')
            ->where($where)
            ->field(['uuid', 'name'])
            ->select();

        $searchWhere = [
            ['m.projectCode', '=', $request->prjCode],
            ['md.wxappUserUuid', '=', $request->uuid],
            ['md.isDelete', '=', 0],
            ['m.isDelete', '=', 0],
            ['m.status', '=', 1],
        ];
        $data['machineList'] = DB::table('certificate_digitalMachineDriver')
            ->alias('md')
            ->join('certificate_digitalMachine m', 'm.uuid=md.digitalMachineUuid')
            ->field(['m.name', 'm.uuid', 'm.subtitle'])
            ->where($searchWhere)
            ->select();

        return result(SUCCESS, $data, '');
    }

    public function hasAuth($request, $data)
    {
        //是否有新增权限,具有申请表权限+驾驶舱人员
        $hasAuth =  0;
        $searchWhere = [
            ['a.wxappUserUuid', '=', $request->uuid],
            ['w.isDelete', '=', 0],
            ['a.isDay', '=', 1],
            ['m.status', '=', 1],
            ['t.isDelete', '=', 0],
            ['a.isDelete', '=', 0],
        ];
        if (!empty($data['machineUuid'])) {
            array_push($searchWhere, ['m.uuid', '=', $data['machineUuid']]);
        }
        $auth =  DB::table('certificate_heavyMachineCheckTypeAuth')->alias('a')
            ->join('certificate_areaType t', 't.typeUuid=a.typeUuid')
            ->join('certificate_areaWorker w', 'w.areaUuid=t.areaUuid')
            ->join('certificate_digitalMachineType mt', 'a.typeUuid=mt.heavyMachineCheckTypeUuid')
            ->join('certificate_digitalMachine m', 'm.digitalMacineTypeUuid=mt.uuid')
            ->join('certificate_digitalMachineDriver d', 'd.digitalMachineUuid = m.uuid')
            ->where($searchWhere)
            ->find() ? 1 : 0;
        if (!empty($auth)) $hasAuth =  1;
        return $hasAuth;
    }
}
